import React, {Component} from 'react';
import store  from './store';
import TodoListUI from './TodoListUI';

import {getInputChangeAction, getTodoAddAction, getTodoDelAction, getTodoList} from './store/createActions';

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleBtnSubmit = this.handleBtnSubmit.bind(this);
    this.handleItemDel = this.handleItemDel.bind(this);

    store.subscribe(this.handleStoreChange);
  }

  componentDidMount() {
    const action = getTodoList();
    store.dispatch(action);

    // 使用 redux-thunk 可以将异步代码移到createActions中执行
    /*axios.get('/list.json')
      .then((res) => {
        console.log(res.data);
        const action = getInitAction(res.data);
        store.dispatch(action);
      })*/
  }

  render() {
    return (
      <TodoListUI
        inputValue={this.state.inputValue}
        list={this.state.list}
        handleInputChange={this.handleInputChange}
        handleBtnSubmit={this.handleBtnSubmit}
        handleItemDel={this.handleItemDel}
      />
    );
  }

  handleInputChange(e) {
    const action = getInputChangeAction(e.target.value);
    store.dispatch(action);
  }

  handleBtnSubmit() {
    const action = getTodoAddAction();
    store.dispatch(action);
  }

  handleItemDel(index) {
    const action = getTodoDelAction(index);
    store.dispatch(action);
  }

  handleStoreChange() {
    this.setState(store.getState());
  }

}

export default TodoList;